package com.cobla.struct.lineartable;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 双链表
 * @date 2019/8/24
 * @author wt
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DLnode {
    private int data;
    private DLnode prior;
    private DLnode next;

    /**
     * 尾插法建立双向链表
     * @param a 元素
     * @param n 数组实际存储个数
     * @return
     */
    public static DLnode createDListR(int a[], int n) {
        DLnode head = new DLnode(0, null, null);
        DLnode pointer = head;
        for (int i = 0; i < n; i++) {
            pointer.next = new DLnode(a[i], pointer, null);
        }
        return head;
    }

    /**
     * 查找指定大小的节点结点
     * @param x
     * @return 找不到返回null
     */
    public DLnode findNode(int x) {
        DLnode p = this;
        while (p.next != null) {
            if (p.next.data == x) {
                return p.next;
            }
            p = p.next;
        }
        return null;
    }

    /**
     * 在指定节点后面插入节点的模板代码
     * @param prior 指定节点
     * @param inserted 待插入节点
     */
    public static void insertedAfterDLNode(DLnode prior, DLnode inserted) {
        inserted.next = prior.next;
        inserted.prior = prior;
        prior.next = inserted;
        inserted.next.prior = inserted;
    }

}
